package com.wzdigit.wms.wms.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicGetCustomerApi;
import com.wzdigit.mes.basic.api.BasicSimpleCodeRuleApi;
import com.wzdigit.mes.basic.dto.CustomerDto;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.inventory.Lotno;
import com.wzdigit.wms.basic.domain.mid.IfSalesreturnDtl;
import com.wzdigit.wms.basic.domain.mid.IfSalesreturnHeader;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.domain.mid.dtos.IfSalesreturnHeaderDto;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.mid.IfSalesreturnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.mid.IfSalesreturnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.wms.constant.SyncTypeConstant;
import com.wzdigit.wms.wms.exception.SyncException;
import com.wzdigit.wms.basic.service.code.LotnoService;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-销售退货单表头 服务实现类
 * </p>
 *
 * @author
 * @since 2021-03-16
 */
@Service
public class IfSalesreturnHeaderService {

    @Autowired
    private IfSalesreturnHeaderMapper ifSalesreturnHeaderMapper;

    @Autowired
    private IfSalesreturnDtlMapper ifSalesreturnDtlMapper;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;

    @Autowired
    private AsnDtlMapper asnDtlMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private LotnoService lotnoService;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Reference(version = "${dubbo.providers.basic.customer.api.version:1.0.0}", check = false, timeout = 300000)
    private BasicGetCustomerApi basicGetCustomerApi;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;

    @Reference(version = "${dubbo.consumers.basic.simple.code.rule.api:1.0.0}", check = false)
    BasicSimpleCodeRuleApi basicSimpleCodeRuleApi;

    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;

    private final String ASN_NO = "ASN_R04";

    private final String syncType = SyncTypeConstant.IF_SALESRETURN_TO_ASN;

    public List<IfSalesreturnHeaderDto> selectSyncData() {
        ArrayList<IfSalesreturnHeaderDto> ifSalesreturnHeaderDtos = new ArrayList<>();
        List<IfSalesreturnHeader> selectSyncData = ifSalesreturnHeaderMapper.selectList(new QueryWrapper<>(new IfSalesreturnHeader().setAttribute10("0")));
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfSalesreturnHeader ifSalesreturnHeader : selectSyncData) {
                IfSalesreturnHeaderDto ifSalesreturnHeaderDto = new IfSalesreturnHeaderDto();
                BeanUtil.copyNonNull(ifSalesreturnHeader, ifSalesreturnHeaderDto);
                List<IfSalesreturnDtl> ifSalesreturnDtls = ifSalesreturnDtlMapper.selectList(new QueryWrapper<>(
                        new IfSalesreturnDtl().setIfSalesreturnHeaderId(ifSalesreturnHeader.getIfSalesreturnHeaderId())
                ));
                ifSalesreturnHeaderDto.setIfSalesreturnDtlList(ifSalesreturnDtls);
                ifSalesreturnHeaderDtos.add(ifSalesreturnHeaderDto);
            }

        }
        return ifSalesreturnHeaderDtos;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncData(IfSalesreturnHeaderDto data, boolean isSyncError) throws Exception {
        String salesReturnNo = data.getSalesReturnNo();
        List<IfSalesreturnDtl> ifSalesreturnDtlList = data.getIfSalesreturnDtlList();
        AsnHeader asnHeader = new AsnHeader();
        CustomerDto customer = basicGetCustomerApi.getCustomerByCode(data.getCustomerCode());
        if (customer == null) {
            throw new SyncException(syncType, salesReturnNo, "客户" + data.getCustomerCode() + "不存在");
        }
        asnHeader.setSourceNo(salesReturnNo);
        asnHeader.setCustomerId(customer.getCustomerId());
        asnHeader.setAsnRef1(customer.getCustomerName());
        asnHeader.setFactory(data.getOrgCode());
        asnHeader.setActualarrivetime(data.getSalesReturnTime());
        asnHeader.setAsnCreateTime(data.getCreateTime());
        asnHeader.setAsnCreateTime(data.getCreateTime());
        asnHeader.setComments(data.getRemarks());
        asnHeader.setAsnType(AsnTypeEnum.R04.getCode());
        asnHeader.setReleaseStatus(1);
        asnHeader.setQcStatus(QcStatusEnum.已创建质检单.getCode());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDataItemDetailByPCodeAndName(DEFAULT_OWNER, DEFAULT_OWNER_NAME);
        asnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0 : Integer.parseInt(dataItem.getItemValue()));
        AsnHeader asnHeaderRecord = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setSourceNo(salesReturnNo)));
        if (asnHeaderRecord == null) {
            asnHeader.setCreateTime(new Date());
            asnHeader.setAsnCreateUser("system");
            //加个创建人--YWB
            asnHeader.setCreateUser("system");
            asnHeader.setAsnNo(basicSimpleCodeRuleApi.GenerateCode(ASN_NO));
            //加个状态--YWB
            asnHeader.setStatus(AsnHeaderStatusEnum.CREATE.getCode());//新建状态
            asnHeaderMapper.insert(asnHeader);
        } else {
            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeader.setAsnHeaderId(asnHeaderRecord.getAsnHeaderId());
            asnHeader.setAsnNo(asnHeaderRecord.getAsnNo());
            asnHeaderMapper.updateById(asnHeader);
        }
        Integer asnLineNo = 0;
        for (IfSalesreturnDtl ifSalesreturnDtl : ifSalesreturnDtlList) {
            AsnDtl asnDtl = new AsnDtl();

            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setSourceNo(salesReturnNo);
            asnDtl.setSourceLineNo(ifSalesreturnDtl.getSalesReturnLineNo());
            asnDtl.setPoNo(ifSalesreturnDtl.getPoNo());
            asnDtl.setPoLineNo(ifSalesreturnDtl.getPoLineNo());
            asnDtl.setSoNo(ifSalesreturnDtl.getSoNo());
            asnDtl.setSoLineNo(ifSalesreturnDtl.getSoLineNo());
            Sku sku = skuMapper.selectOne(new QueryWrapper<>(new Sku().setSkuCode(ifSalesreturnDtl.getMaterialCode())));
            if (sku == null) {
                throw new SyncException(syncType, salesReturnNo, "物料" + ifSalesreturnDtl.getMaterialCode() + "不存在");
            }
            asnDtl.setSkuId(sku.getSkuId());
            asnDtl.setSkuDesc(sku.getDescCn());
            asnDtl.setSkuDescEn(sku.getDescEn());
            asnDtl.setUnit(sku.getBaseUnit());
            asnDtl.setOrderQty(ifSalesreturnDtl.getSalesReturnQty());
            asnDtl.setOrderQtyEa(ifSalesreturnDtl.getSalesReturnQty());
            asnDtl.setComments(ifSalesreturnDtl.getRemarks());
            asnDtl.setQcStatus(QcStatusEnum.未创建质检单.getCode());
            asnDtl.setQaStatus(QaStatusEnum.OK.getCode());
            AsnDtl asnDtlRecord = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnNo(asnHeader.getAsnNo()).setAsnLineNo(ifSalesreturnDtl.getSalesReturnLineNo())));
            if (asnDtlRecord == null) {
                asnDtl.setCreateUser("system");
                asnDtl.setCreateTime(new Date());
                asnDtl.setStatus(AsnDtlStatusEnum.CREATE.getCode());//新建状态
                asnDtl.setAsnLineNo(String.valueOf(++asnLineNo));//加个ASN_LINE_NO
                asnDtl.setAsnNo(asnHeader.getAsnNo());//加个ASN_NO

                try {
                    asnDtlMapper.insert(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, salesReturnNo, e.getMessage());
                }
            } else {
                asnDtl.setModifyUser("system");
                asnDtl.setModifyTime(new Date());
                asnDtl.setAsnDtlId(asnDtlRecord.getAsnDtlId());
                try {
                    asnDtlMapper.updateById(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, salesReturnNo, e.getMessage());
                }
            }
            //生成批次号
            Lotno lotno = lotnoService.getLotnoByAsnDtlId(asnDtl.getAsnDtlId());
            if (lotno != null) {
                asnDtl.setLotno(lotno.getLotno());
                int r = 1;
                try {
                    r = setLotAttr(asnDtl, lotno);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, salesReturnNo, "设置批次属性" + r + "失败");
                }
                asnDtlMapper.updateLotNoAndAttr(asnDtl);
            }
            //更新状态为已同步
            int row = ifSalesreturnHeaderMapper.updateFlagById(data.getIfSalesreturnHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, salesReturnNo);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, salesReturnNo);
            }
        }
        //TODO 测试代码，测试和投产记得删除
//        int a = 0 / 0;
    }

    /**
     * 设置批次属性1~12
     *
     * @param obj
     * @param lotno
     */
    private int setLotAttr(Object obj, Lotno lotno) throws Exception {
        int i = 1;
        for (i = 1; i < 13; i++) {
            try {
                Class<?> aClass = obj.getClass();
                Object value = lotno.getClass().getMethod("getLotAttr" + i).invoke(lotno, null);
                Method method = aClass.getMethod("setLotAttr" + i, String.class);
                method.invoke(obj, value);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
        return i;
    }
}
